package com.gmq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmq.common.BaseContext;
import com.gmq.common.CustomExcetion;
import com.gmq.common.R;
import com.gmq.dto.OrdersDto;
import com.gmq.entity.*;
import com.gmq.mapper.OrderMapper;
import com.gmq.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private BaseContext baseContext;

    @Override
    public void submit(Orders orders) {
        Long userid = baseContext.getThreadLocal();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        //查询购物车数据
        queryWrapper.like(ShoppingCart::getUserId, userid);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        //生成订单号
        long id = IdWorker.getId();
        if (list.size() == 0 || list == null) {
            throw new CustomExcetion("购物车为空,无法下单");
        }
        //保证在多并发的环境下也能正常计算
        AtomicInteger amount = new AtomicInteger(0);
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            //往订单明细表插入数据(多条数据)
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setOrderId(id);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setImage(shoppingCart.getImage());
            //转换成int类型相乘
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            orderDetailService.save(orderDetail);
        }
        //查询用户表
        User userServiceById = userService.getById(userid);
        //查询地址表
        AddressBook bookServiceById = addressBookService.getById(orders.getAddressBookId());

        //往订单表插入数据
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setNumber(String.valueOf(id));
        orders.setUserId(userid);
        orders.setStatus(2);
        orders.setUserName(userServiceById.getName());
        orders.setPhone(bookServiceById.getPhone());
        orders.setAddress(bookServiceById.getDetail());
        orders.setConsignee(bookServiceById.getConsignee());
        orders.setAmount(new BigDecimal(amount.get()));
        save(orders);
        //清空购物车
        shoppingCartService.remove(queryWrapper);
    }

    @Override
    public Page<OrdersDto> userPage(int page_, int pageSize) {
        Page<Orders> page1 = new Page(page_, pageSize);
        Page<OrdersDto> page2 = new Page<>();
        Long userid = baseContext.getThreadLocal();

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Orders::getUserId, userid);
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        page(page1, queryWrapper);

        BeanUtils.copyProperties(page1, page2, "records");
        List<OrdersDto> ordersDtoList = new ArrayList<>();
        for (Orders record : page1.getRecords()) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record, ordersDto);
            AddressBook bookServiceById = addressBookService.getById(record.getAddressBookId());
            User userServiceById = userService.getById(userid);
            ordersDto.setUserName(userServiceById.getName());
            ordersDto.setPhone(bookServiceById.getPhone());
            ordersDto.setAddress(bookServiceById.getDetail());
            ordersDto.setConsignee(bookServiceById.getConsignee());

            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();

            queryWrapper1.eq(OrderDetail::getOrderId, record.getNumber());

            List<OrderDetail> list = orderDetailService.list(queryWrapper1);

            ordersDto.setOrderDetails(list);
            ordersDtoList.add(ordersDto);
        }
        page2.setRecords(ordersDtoList);
        return page2;
    }
}
